Ext.require([
             'Ext.grid.*',
             'Ext.data.*',
             'Ext.ux.grid.FiltersFeature',
             'Ext.toolbar.Paging',
             'Ext.ux.ajax.JsonSimlet',
             'Ext.ux.ajax.SimManager',
             'Ext.ux.grid.Printer'        
]);
Ext.FocusManager.enable(true);
Ext.define('TS.controller.RejectStockInBillEditorCtl',{
	extend: 'Ext.app.Controller',
	
	models:['common.BillAmountModel','common.BillExtendModel','common.InventoryAddModel','common.BillHistoryModel',
	'pur.RejectStockInBillModel','pur.RejectStockInBillDetailModel'],
	stores:['pur.RejectStockInBillStore','pur.RejectStockInBillDetailStore','common.BillHistoryStore'],
	views:['pur.RejectStockInBillList','pur.RejectStockInBillEditor','common.BillHistorySimpleList','common.BillHistoryBrowseDialog'],
	init:function() {
		this.control({
			'rejectinbilleditor button[action=saveBill]':{click:this.onSaveBill},
			'rejectinbilleditor button[action=archiveBill]':{click:this.onArchiveBill},
			'rejectinbilleditor button[action=unArchiveBill]':{click:this.onUnArchiveBill},
			'rejectinbilleditor button[action=printBill]':{click:this.onPrintBill},
			'rejectinbilleditor button[action=addprod]':{click:this.onEditDetail},
			'rejectinbilleditor button[action=linkbill]':{click:this.onLinkBill},
			'rejectinbilleditor button[action=reset]':{click:this.onClearDetailEditor},
			'rejectinbilleditor triggerfield[name=customerCode]':{specialkey:this.editorSearchCustormer},
			'rejectinbilleditor triggerfield[name=productCode]':{specialkey:this.onSearchProduct},
			'rejectinbilleditor triggerfield[name=batchNo]':{specialkey:this.onSearchProductBatchNo},
			'rejectinbilleditor':{cellSpecialkey:this.onCellediting},
			'rejectinbilleditor grid[name=rejectinbilldetails]':{itemdblclick:this.onDbclickBillDetail}
		});
	},
	onSaveBill:function(button){
		var mform=button.up('panel').down('form');
		var record = mform.getRecord(),
        values = mform.getValues();
        record.set(values);
        
        var grid=button.up('panel').query('grid')[0];
        var data =record.getData(true);
        delete data.billAmount;
        Ext.Array.each(data.details,function(d){
        	delete d.amount;
        	delete d.product;
        	delete d.batchNo;
        })
        Ext.Ajax.request({
				    url:'inreject/save.do',
				    method : 'POST',
				    timeout :3000,
				    jsonData:data,
				    success:function(response){		
				    	var rs=Ext.decode(response.responseText);
				    	if(rs.success==true){
				    		record.set('billId',rs.o.billId);
				    		mform.loadRecord(record);
				    		grid.getStore().each(function(detail){
				    			detail.set('billId',rs.o.billId)
				    		});
					    	grid.getStore().commitChanges();
					    }
				    	showExtReturnMsg(response);
				    }
	    });
	},
	onArchiveBill:function(button){
		var mform=button.up('panel').down('form');
		var grid =button.up('panel').query('grid')[0];
		var bill = mform.getRecord();
    	if(grid.getStore().getModifiedRecords().length>0 ||
    	   grid.getStore().getRemovedRecords().length>0){
    		Ext.Msg.show({
	   			title:'ThinkGsp',
	   			msg:'单据未保存, 不能归档!',
	   			buttons:Ext.Msg.OK,
	   			icon:Ext.Msg.WARNING
	   		 });
	   		 return;
    	}
		if(bill.get('billId') || bill.get('billId') != 0) {
 			if(bill.get('archived')) {
				Ext.Msg.show({
						title:'ThinkGsp',
						msg:'单据已经归档!',
						buttons:Ext.Msg.OK,
						icon:Ext.Msg.WARNING
				});
				return;
			}
			Ext.Ajax.request({
					    url:'inreject/archive.do',
					    method : 'POST',
					    timeout :3000,
					    params:{billId:bill.get('billId')},
					    success:function(response){		
					    	var rs=Ext.decode(response.responseText);
					    	if(rs.success==true){
					    		bill.set('archived',true);
						    	this.onUpdateState(button.up('panel'),bill);
						    }
					    	showExtReturnMsg(response);
					    },
					    scope:this
		    });
		}else{
			Ext.Msg.show({
	   			title:'ThinkGsp',
	   			msg:'单据未保存, 不能归档!',
	   			buttons:Ext.Msg.OK,
	   			icon:Ext.Msg.WARNING
	   		 });
	   		 return;
		}
	},
	onUpdateState:function(editor,bill) {
    	 if(bill.get('archived')) {
    		 editor.down('button[action=archiveBill]').setDisabled(true);
    		 editor.down('button[action=saveBill]').setDisabled(true);
    		 editor.down('button[action=unArchiveBill]').setDisabled(false);
    	 } else {
    		 editor.down('button[action=saveBill]').setDisabled(false);
    		 editor.down('button[action=archiveBill]').setDisabled(false);
    		 editor.down('button[action=unArchiveBill]').setDisabled(true);
    	 }
    	 if(bill.get('billId') == 0) {
    		 editor.setTitle('入库退货单-新增');
    		 editor.down('triggerfield[name=customerCode]').focus(true,100);
    	 } else if(bill.get('archived')) {
			 editor.setTitle('入库退货单-查看');
		 } else {
			 editor.setTitle('入库退货单-编辑');
			 editor.down('triggerfield[name=productCode]').focus(true,100);
		 }
    },
	onUnArchiveBill:function(button){
		var mform=button.up('panel').down('form');
		var bill = mform.getRecord();
		if(bill.get('billId') || bill.get('billId') != 0) {
 			if(!bill.get('archived')) {
				Ext.Msg.show({
						title:'ThinkGsp',
						msg:'单据已经反归档!',
						buttons:Ext.Msg.OK,
						icon:Ext.Msg.WARNING
				});
				return;
			}
			Ext.Ajax.request({
					    url:'inreject/unArchive.do',
					    method : 'POST',
					    timeout :3000,
					    params:{billId:bill.get('billId')},
					    success:function(response){		
					    	var rs=Ext.decode(response.responseText);
					    	if(rs.success==true){
						    	if(rs.success==true){
						    		bill.set('archived',false);
							    	this.onUpdateState(button.up('panel'),bill);
							    }
						    }
					    	showExtReturnMsg(response);
					    },
					    scope:this
		    });
		}else{
			Ext.Msg.show({
	   			title:'ThinkGsp',
	   			msg:'单据未保存, 不能反归档!',
	   			buttons:Ext.Msg.OK,
	   			icon:Ext.Msg.WARNING
	   		 });
	   		 return;
		}
	},
	onPrintBill:function(button){
		var mform=button.up('panel').down('form');
		var bill = mform.getRecord();
		if(bill.get('billId') || bill.get('billId') != 0) {
	     	window.open('inreject/getpdfReport.do?billId='+bill.get('billId'));
		}
	},
	onExportBill:function(button){
		
	},
	editorSearchCustormer:function(field,e){
		if(e.getKey() == e.ENTER && field.value != '') {
	    	var view=Ext.create('TS.view.base.CustomerSearchDialog');
	    	view.setVal(field.value);
	    	view.on({
			    selected: function(records){
			    	if(records.length == 0) {
			    		Ext.MessageBox.alert('ThinkGsp','未检索到任何客户信息!');
			    	} else {
			    		field.setValue(records[0].get('customerCode'));
						var form = field.up('form');
				    	var nameField = form.down('textfield[name=customerName]');
				    	nameField.setValue(records[0].get('customerName'));
				    
				    	form.getRecord().setcustomer(records[0]);
				    	form.getRecord().set('custId',records[0].get('customerId'));
				    	form.up('panel').down('triggerfield[name=productCode]').focus(true,100);
			    	}
			    },
			    scope: this
			});
	   	 	view.show();	
    	}  
	},
	onAdvsearch:function(button){
		
	},
	onCellediting:function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts ){
		alert(111);
	},
	onSearchProduct:function(field,e){
		if(e.getKey() == e.ENTER ){
			var form=field.up('form');
			var mform=form.up('panel').down('form');
			var bill = mform.getRecord();
			if(Ext.isEmpty(bill.get('custId')) || bill.get('custId')==0){
				Ext.Msg.show({title:'ThinkGSP',msg:'请先选择客户!!',buttons:Ext.Msg.OK,icon:Ext.Msg.WARNING});
				return;
			}
			var bform=form.down('form');
			var win=Ext.create('TS.view.base.ProductSearchDialog');
			win.setVal(field.value);
			win.on({
			    selected: function(records){
			    	if(records){
			    		if(records.length>0){
			    			form.loadRecord(records[0]);	    			
			    			form.down('numberfield[name=quantity]').decimalPrecision=records[0].get('qtyScale');
			    			form.down('numberfield[name=price]').decimalPrecision=records[0].get('priceScale');
			    			form.down('combobox[name=invAddId]').focus(true,100);
			    			//var bform=form.down('form');
			    			//bform.down('triggerfield[name=batchNo]').setDisabled(!records[0].get('batchMgr'));
			    			if(records[0].get('batchMgr')==false){
			    				var st=Ext.create('TS.store.inv.ProductBatchNoStore');
    							st.load({
									params:{prodId:records[0].get('productId')},
						    		callback:function(rs, operation, success){
						    			if(rs){
							    			if(rs.length>0){
							    				bform.loadRecord(rs[0]);
							    			}
						    			}
						    		},
							   		scope: this
								});				
			    			}
			    		}
			    	}
			    	win.close();
			    },
			    scope: this
			});
			win.show();
		}
	},
	onSearchProductBatchNo:function(field,e){
		if(e.getKey() == e.ENTER ){
			var bform=field.up('form');
			var pform=bform.up('form');
			var prod=pform.getRecord();
			
			if(prod && prod.get('productId')>0){
				var view=Ext.create('TS.view.inv.ProductBatchNoDialog');
				var pid=prod.get('productId');
				view.setProdId(pid);
		    	view.setPrecord(prod);
		    	view.on({
				    selected: function(records){
				    	if(records){
				    		if(records.length>0){
				    			if(records[0].get('productId')!=pid){
				    				Ext.Msg.show({title:'ThinkGSP',msg:'选择批号商品与当前商品不同,请重新选择!',buttons:Ext.Msg.OK,icon:Ext.Msg.WARNING});
				    				return ;
				    			}
				    			bform.loadRecord(records[0]);
				    			pform.down('numberfield[name=quantity]').focus(true,100);
				    		}
				    	}
				    	view.close();
				    },
				    scope: this
				});
		    	view.show();
			}else{
				Ext.Msg.show({title:'ThinkGSP',msg:'未选择商品!',buttons:Ext.Msg.OK,icon:Ext.Msg.WARNING});
			}
		}
	},
	onEditDetail:function(btn){
		var editor=btn.up('form').up('panel');
		var mform=editor.down('form');
		var grid =editor.query('grid')[0];
		var mv=mform.getValues();		
		var pform=btn.up('form');
		var pv=pform.getValues();
		var bform=pform.down('form');
		var bv=bform.getValues();
		var detail=null;
		if(btn.text=='添加'){
			detail=Ext.create('TS.model.pur.RejectStockInBillDetailModel');
		}
		if(btn.text=='编辑'){
			var rs=grid.getSelectionModel().getSelection();
			if(rs && rs.length > 0){
				detail=rs[0];	
			}
		}
		
		if(!pv.invAddId || pv.invAddId==0){
			Ext.Msg.show({title:'ThinkGSP',msg:'请选择退货货位!',buttons:Ext.Msg.OK,icon:Ext.Msg.WARNING});
			return;
		}
		if(!bv.id || bv.id==0){
			Ext.Msg.show({title:'ThinkGSP',msg:'请选择批号,如批号不存在请在弹出窗口先添加该批号!',buttons:Ext.Msg.OK,icon:Ext.Msg.WARNING});
			return;
		}
		detail.set('billId',mv.billId);
		detail.set('quantity',pv.quantity);
		detail.set('price',pv.price);
		detail.set('settlePrice',pv.price);
		detail.set('productId',pv.productId);
		detail.set('amount',pv.quantity*pv.price);
		detail.set('batchNoId',bv.id);
		detail.set('direct',0);
		detail.set('invAddId',pv.invAddId);
		detail.set('taxRate',pv.taxRate);
		//amount,batchNoId,billId,costPrice,direct,id,invAddId,price,productId,remark,settlePrice,taxRate
		/*if(detail.get('id') && detail.get('id')>0){
			detail.set('product',pform.getRecord());
			detail.set('batchNo',bform.getRecord());
		}else{
			detail.product=pform.getRecord();
			detail.batchNo=bform.getRecord();
		}*/
		detail.product=pform.getRecord();
		if(Ext.isEmpty(bform.getRecord())){
			var batno=Ext.create("TS.model.inv.ProductBatchNoModel");
			batno.set("id",bv.id);
			batno.set("batchNo",bv.batchNo);
			batno.set("manufDate",bv.manufDate);
			batno.set("expDate",bv.expDate);
			bform.loadRecord(batno);
		}
		detail.batchNo=bform.getRecord();

		if(btn.text=='添加'){
			grid.store.insert(0,detail); 
			pform.getForm().reset(true);
			bform.getForm().reset(true);
		}
		//grid.getStore().commitChanges();
		grid.getView().refresh();
	},
	onDbclickBillDetail:function(grid,record){
		var editor=grid.up('panel').up('panel');
		var forms=editor.query('form');
		var pform=forms[1];
		var bform=forms[2];
		if(!Ext.isEmpty(record.product)){
	 		pform.loadRecord(record.product);
	 	}else{
			pform.loadRecord(record.getproduct());
	 	}
		pform.down('combobox[name=invAddId]').setValue(record.get('invAddId'));
		if(!Ext.isEmpty(record.product)){
	 		bform.loadRecord(record.batchNo);
	 	}else{
			bform.loadRecord(record.getbatchNo());
	 	}
	 	var prod=pform.getRecord();
	 	pform.down('numberfield[name=quantity]').decimalPrecision=prod.get('qtyScale');
		pform.down('numberfield[name=price]').decimalPrecision=prod.get('priceScale');
		pform.down('numberfield[name=quantity]').setValue(record.get('quantity'));
		pform.down('numberfield[name=price]').setValue(record.get('price'));
		editor.down('button[action=addprod]').setText('编辑');
	},
	onClearDetailEditor:function(btn){
		var editor=btn.up('form').up('panel');
		//var mform=editor.down('form');	
		var pform=btn.up('form');
		pform.getForm().reset(true);
		var bform=pform.down('form');
		bform.getForm().reset(true);
		editor.down('button[action=addprod]').setText('添加');
	},
	onLinkBill:function(btn){
		var editor=btn.up('form').up('panel');
		var mform=editor.down('form');
		var pform=btn.up('form');
		var prod=pform.getRecord();
		var bform=pform.down('form');
		var bill = mform.getRecord();
		if(Ext.isEmpty(bill.get('custId')) || bill.get('custId')==0){
			Ext.Msg.show({title:'ThinkGSP',msg:'请先选择客户!!',buttons:Ext.Msg.OK,icon:Ext.Msg.WARNING});
			return;
		}	
		if(prod && prod.get('productId')>0){
			var view=Ext.create('TS.view.common.BillHistoryBrowseDialog');
			var pid=prod.get('productId');
			var cid=bill.get('custId');
			view.setProductId(pid);
	    	view.setCustId(cid);
	    	view.setEndDate(new Date());
	    	var d=new Date();
	    	d.setDate(d.getDate()-365)
	    	view.setBegDate(d);
	    	view.setIsSale(false);
	    	view.on({
			    selected: function(records){
			    	if(records){
			    		if(records.length>0){
			    			//Ext.Msg.show({title:'ThinkGSP',msg:records[0].get("billCode"),buttons:Ext.Msg.OK,icon:Ext.Msg.WARNING});
			    			pform.down('combobox[name=invAddId]').setValue(records[0].get("invAddId"));
			    			bform.down('triggerfield[name=batchNo]').setValue(records[0].get("batchNo"));
			    			bform.down('datefield[name=manufDate]').setValue(records[0].get("manufDate"));
			    			bform.down('datefield[name=expDate]').setValue(records[0].get("expDate"));
			    			bform.down('hiddenfield[name=id]').setValue(records[0].get("batchNoId"));
			    			pform.down('numberfield[name=price]').setValue(records[0].get("settlePrice"));
			    			pform.down('numberfield[name=quantity]').setValue(0-records[0].get("quantity"));
			    			pform.down('numberfield[name=quantity]').focus(true,100);
			    		}
			    	}
			    	view.close();
			    },
			    scope: this
			});
	    	view.show();
		}else{
			Ext.Msg.show({title:'ThinkGSP',msg:'未选择商品!',buttons:Ext.Msg.OK,icon:Ext.Msg.WARNING});
		}
	}
});